<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> {{ myFormTitle }} </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-form ref="form" label-width="80px" :inline="true">
                    <el-form-item label="筛选条件">
                        <el-input
                            placeholder="商品编号、名称或备注模糊筛选"
                            class="handle-input mr10"
                            v-model="query.FilterPara"
                        ></el-input>
                    </el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                    <!-- <el-button type="primary" icon="el-icon-plus" @click="handleCreate">新建</el-button> -->
                    <!-- <el-button type="primary" icon="el-icon-folder-add" @click="getFile">上传</el-button> -->

                    <el-button type="primary" icon="el-icon-folder-add" @click="uploadDialogVisible = true">上传</el-button>
                    <el-form-item>
                        <input
                            id="app"
                            ref="file"
                            type="file"
                            name="file"
                            @change="importfxx(this)"
                            style="display: none;"
                            accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                        />
                    </el-form-item>
                </el-form>
            </div>
            <el-table
                ref="multipleTable"
                :data="tableData"
                highlight-current-row
                style="width: 100%"
                fit
                border
                @selection-change="handleSelectionChange"
            >
                <el-table-column label="商品id" align="center" v-if="show">
                    <template slot-scope="scope">{{ scope.row.FProductID }}</template>
                </el-table-column>
                <el-table-column label="商品代码" align="center">
                    <template slot-scope="scope">{{ scope.row.FProductNo }}</template>
                </el-table-column>
                <el-table-column label="商品名称" align="center">
                    <template slot-scope="scope">{{ scope.row.FProductName }}</template>
                </el-table-column>
                <el-table-column label="类别" align="center">
                    <template slot-scope="scope">{{ scope.row.FType }}</template>
                </el-table-column>
                <el-table-column label="价格" align="center">
                    <template slot-scope="scope">{{ scope.row.FPrice }}</template>
                </el-table-column>
                <el-table-column label="操作" width="250" align="center" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.FPageIndex"
                    :page-size="query.FPageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog :title="showDialogTitle" :visible.sync="dialogVisible" width="30%" @close="editCloseDialog">
            <el-form ref="editForm" :model="editForm" label-width="100px">
                <el-form-item label="商品id" v-if="show"> <el-input v-model="editForm.FProductID"></el-input> </el-form-item>
                <el-form-item label="商品代码"> <el-input v-model="editForm.FProductNo"></el-input> </el-form-item>
                <el-form-item label="商品名称"> <el-input v-model="editForm.FProductName"></el-input> </el-form-item>
                <el-form-item label="商品价格"> <el-input v-model="editForm.FPrice"></el-input> </el-form-item>
                <el-form-item label="商品类别">
                    <el-select v-model="editForm.FType">
                        <el-option v-for="item in options" :key="item.FType" :label="item.label" :value="item.FType"> </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 上传弹出框 -->
        <el-dialog title="Excel上传" :visible.sync="uploadDialogVisible" width="30%" @close="editCloseDialog">
            <el-form ref="uploadForm" :model="uploadForm" label-width="100px">
                <el-form-item>
                    <el-upload
                        class="upload-demo"
                        ref="upload"
                        action="https://www.jiangnanzhizaofu.com/WechatSystem/FileUpload.ashx"
                        drag
                        :auto-upload="false"
                        :headers="headers"
                        :before-upload="beforeUpload"
                        :on-success="handleFilUploadSuccess"
                        :on-remove="handleRemove"
                        :on-error="handleUploadError"
                        :on-progress="uploadFileProcess"
                        :limit="1"
                        accept=".xlsx,.xls"
                    >
                        >
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">
                            上传文件大小不超过100MB
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitUpload('uploadForm')">确 定</el-button>
                <el-button @click="uploadDialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { fetchDataFromApi, fetchDataFromApiPost } from '../../api/apiService';
import { Loading } from 'element-ui';
import axios from 'axios';
import XLSX from 'xlsx'; //引入

export default {
    name: 'basetable',
    data() {
        return {
            headers: { Token: window.localStorage.getItem('ms_token') },
            multipleSelection: [],
            array: [],
            show: false,
            currentPage1: 1,
            showDialogTitle: '',
            dialogVisible: false,
            uploadDialogVisible: false,
            myFormTitle: '商品档案管理 / 数据清单',
            options: [
                {
                    FType: '丝巾',
                    label: '丝巾'
                },
                {
                    FType: '成衣',
                    label: '成衣'
                },
                {
                    FType: '中装',
                    label: '中装'
                },
                {
                    FType: '饰品',
                    label: '饰品'
                },
                {
                    FType: '家居生活',
                    label: '家居生活'
                }
            ],
            value: [],
            pageTotal: 0,
            query: {
                FilterPara: '',
                FPageIndex: 1,
                FPageSize: 10
            },
            form: {
                FProductID: '',
                FProductNo: '',
                FProductName: '',
                FType: '',
                FPrice: ''
            },
            editForm: {
                FProductID: '',
                FProductNo: '',
                FProductName: '',
                FType: '',
                FPrice: ''
            },
            tableData: [],

            arr: [],
            uploadForm: {}
        };
    },

    created() {
        this.getData();
    },
    methods: {
        clearFile() {
            this.$refs.file.value = ''; // 清空file文件
        },
        //关闭时清空表单
        editCloseDialog() {
            this.edditForm = '';
            this.$refs.upload.clearFiles();
        },
        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
        },
        //表中内容修改时用
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log(val);
        },

        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'FPageIndex', 1);
            //this.query.FPageIndex = 1;
            this.getData();
        },
        //获取数据
        getData() {
            this.listLoading = true;
            this.query.ActionCode = 'SearchProduct';
            this.query.Token = localStorage.getItem('ms_token');
            fetchDataFromApi(this.query).then(res => {
                if (res != undefined && res != null && res != '') {
                    this.tableData = res.data.items;
                    this.pageTotal = res.data.total;
                }
                this.listLoading = false;
            });
        },
        //触发input上传文件
        getFile() {
            this.$refs.file.click();
        },
        //上传excel
        importfxx(obj) {
            let _this = this;
            let inputDOM = this.$refs.inputer;
            // 通过DOM取文件数据
            this.file = event.currentTarget.files[0];
            // console.log(this.file);
            var rABS = false; //是否将文件读取为二进制字符串
            var f = this.file;
            var reader = new FileReader();
            //if (!FileReader.prototype.readAsBinaryString) {
            FileReader.prototype.readAsBinaryString = function(f) {
                var binary = '';
                var rABS = false; //是否将文件读取为二进制字符串
                var pt = this;
                var wb; //读取完成的数据
                var outdata;
                var reader = new FileReader();
                reader.onload = function(e) {
                    var bytes = new Uint8Array(reader.result);
                    var length = bytes.byteLength;
                    for (var i = 0; i < length; i++) {
                        binary += String.fromCharCode(bytes[i]);
                    }
                    var XLSX = require('xlsx');
                    if (rABS) {
                        wb = XLSX.read(btoa(fixdata(binary)), {
                            //手动转化
                            type: 'base64'
                        });
                    } else {
                        wb = XLSX.read(binary, {
                            type: 'binary'
                        });
                    }
                    const sheet2JSONOpts = {
                        /** Default value for null/undefined values */
                        defval: '' //给defval赋值为空的字符串
                    };

                    outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]], sheet2JSONOpts); //outdata就是你想要的东西
                    this.da = [...outdata];
                    let arr = [];
                    this.da.map(v => {
                        let obj = {};
                        obj.FProductNo = v.商品代码;
                        obj.FProductName = v.商品名称;
                        obj.FType = v.商品类别;
                        obj.FPrice = v.商品价格;
                        arr.push(obj);
                    });
                    _this.$message({
                        message: '请耐心等待导入成功',
                        type: 'success'
                    });

                    // console.log(Math.ceil(arr.length / 10));
                    let para = JSON.stringify(arr);
                    var newPara = {};
                    newPara.ActionCode = 'AddProduct';
                    newPara.Token = localStorage.getItem('ms_token');
                    newPara.FUserNo = localStorage.getItem('ms_userno');
                    newPara.ExcelData = para;
                    var param = {};
                    param.ExternalData = newPara;

                    console.log(param);

                    // const a = _this.chunkArr(arr, 10);
                    // console.log(JSON.stringify(a));
                    // for (let j = 0; j < a.length; j++) {
                    //     _this.array = a[j];
                    //     let para = JSON.stringify(_this.array);
                    //     console.log(para);
                    //     var newPara = {};
                    //     newPara.ActionCode = 'AddProduct';
                    //     newPara.Token = localStorage.getItem('ms_token');
                    //     newPara.FUserNo = localStorage.getItem('ms_userno');
                    //     newPara.ExcelData = para;

                    // fetchDataFromApiPost(param).then(res => {
                    //     if (res != undefined && res != null && res != '') {
                    //         console.log(res);
                    //         _this.array = [];
                    //         _this.getData();
                    //     }
                    // });
                    // }

                    _this.clearFile();
                    _this.editVisible = false;

                    // console.log(JSON.parse(para));

                    // var newPara = {};
                    // newPara.ActionCode = 'AddProduct';
                    // newPara.Token = localStorage.getItem('ms_token');
                    // newPara.FUserNo = localStorage.getItem('ms_userno');
                    // newPara.ExcelData = para;

                    // fetchDataFromApi(newPara).then(res => {
                    //     if (res != undefined && res != null && res != '') {
                    //         console.log(res);
                    //         if (res.Message == 'OK') {
                    //             setTimeout(function() {
                    //                 _this.$message.success(res.Info);
                    //                 _this.getData();
                    //             }, 2000);
                    //         } else {
                    //             setTimeout(function() {
                    //                 _this.$message.error(res.Info);
                    //                 _this.getData();
                    //             }, 2000);
                    //         }
                    //     }
                    //     _this.clearFile();
                    //     _this.editVisible = false;
                    // });
                };
                reader.readAsArrayBuffer(f);
            };
            if (rABS) {
                reader.readAsArrayBuffer(f);
            } else {
                reader.readAsBinaryString(f);
            }
        },

        // 根据指定个数分割数组
        chunkArr(arr, size) {
            //判断如果不是数组(就没有length)，或者size没有传值，size小于1，就返回空数组
            if (!arr.length || !size || size < 1) return [];
            let [start, end, result] = [null, null, []];
            for (let i = 0; i < Math.ceil(arr.length / size); i++) {
                start = i * size;
                end = start + size;
                result.push(arr.slice(start, end));
            }
            return result;
        },

        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', { type: 'warning' })
                .then(() => {
                    if (row != undefined && row != null && row != '') {
                        var myRowShopFID = row.FProductID;
                        var querypars = {};
                        querypars.ActionCode = 'DeleteProduct';
                        querypars.Token = localStorage.getItem('ms_token');
                        querypars.FProductID = myRowShopFID;

                        fetchDataFromApi(querypars).then(res => {
                            if (res != undefined && res != null && res != '') {
                                if (res.Message == 'OK') {
                                    this.$message.success(res.Info);
                                    this.getData();
                                } else {
                                    this.$message.error(res.Info);
                                }
                            }
                        });
                    }
                })
                .catch(() => {});
        },
        // 编辑操作
        handleEdit(index, row) {
            this.showDialogTitle = '编辑商品档案信息';
            this.dialogVisible = true;
            this.editForm = Object.assign({}, row);
        },

        //保存编辑
        saveEdit() {
            this.$refs.editForm.validate(valid => {
                if (valid) {
                    if (this.editForm.FProductID == undefined || this.editForm.FProductID == null || this.editForm.FProductID == '')
                        this.editForm.ActionCode = 'AddProduct';
                    else this.editForm.ActionCode = 'UpdateProduct';

                    this.editForm.Token = localStorage.getItem('ms_token');
                    this.editForm.FUserNo = localStorage.getItem('ms_userno');

                    fetchDataFromApi(this.editForm).then(res => {
                        if (res != undefined && res != null && res != '') {
                            if (res.Message == 'OK') {
                                this.$message.success(res.Info);
                                this.getData();
                            } else {
                                this.$message.error(res.Info);
                            }
                        }
                        this.dialogVisible = false;
                    });
                }
            });
        },

        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'FPageIndex', val);
            this.getData();
        },

        handlePageChangeDayTarget(val) {
            this.$set(this.formDay, 'FPageIndex', val);
            this.loadDatTableData();
        },
        //点击上传
        submitUpload(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    console.log('submit!');
                    this.$refs.upload.submit();
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //上传检测
        beforeUpload(file) {
            let isLt2M = true;
            isLt2M = file.size / 1024 / 1024 < 100;
            if (!isLt2M) {
                this.loading = false;
                this.$message.error('上传文件大小不能超过 100MB!');
            } else if (isLt2M == 0) {
                this.loading = false;
                this.$message.error('请选择上传文件');
            }
            // this.form.name = file.name
            return isLt2M;
        },
        // 文件上传成功时的函数
        handleFilUploadSuccess(res, file, fileList) {
            // console.log(res);
            // this.$message.success(res.data);
            let _this = this;
            _this.$refs.upload.clearFiles();
            _this.uploadDialogVisible = false;
            // _this.getData();
            var newPara = {};
            let a = 'C:\\inetpub\\wwwroot\\uploads\\';
            newPara.ActionCode = 'AddProduct';
            newPara.Token = localStorage.getItem('ms_token');
            newPara.FUserNo = localStorage.getItem('ms_userno');
            newPara.ExcelData = a + res.FileName;

            // console.log(newPara);
            _this.$message('文件处理中，请稍后。。。');
            fetchDataFromApi(newPara).then(res => {
                if (res != undefined && res != null && res != '') {
                    // console.log(res);
                    if (res.Message == 'OK') {
                        setTimeout(function() {
                            _this.$message.success(res.Info);
                            _this.getData();
                        }, 2000);
                    } else {
                        setTimeout(function() {
                            _this.$message.error(res.Info);
                            _this.getData();
                        }, 2000);
                    }
                }
            });
        },

        //文件上传过程中的函数(在这里获取进度条的进度)
        uploadFileProcess(event, file, fileList) {
            // console.log(event);
            // console.log(file);
            // console.log(fileList);
        },

        // 文件上传失败时的函数
        handleUploadError(err, file, fileList) {
            // console.log(err.response.data.message);
            // this.$message.error(err.response.data.message);
        },
        //移除
        handleRemove(file, fileList) {
            console.log(file, fileList);
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 220px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>





